<template>
  <a-modal
    v-model:visible="state.visible"
    :unmount-on-close="true"
    :on-before-ok="handleBeforeOk"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ state.module === "create" ? "新增" : "编辑" }}
    </template>
    <a-form :model="state.form" auto-label-width ref="formRef">
      <a-form-item
        field="name"
        label="职位名称"
        :rules="[{ required: true, message: '请输入职位名称' }]"
      >
        <a-input v-model="state.form.name" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { usePositionCreateApi, usePositionUpdateApi } from "@/api";
import { Message } from "@arco-design/web-vue";
import { ref, reactive } from "vue";
const formRef = ref();
const emit = defineEmits(["refresh"]);
const useForm = () => {
  return {
    name: "",
  };
};
const state = reactive({
  form: useForm(),
  module: "update",
  categoryList: [],
  visible: false,
});

const open = (type: string, data: any) => {
  state.module = type;
  console.log(data, "data");
  if (state.module === "update") {
    state.form.name = data.name;
    state.form.code = data.code;
  }
  state.visible = true;
};

const handleBeforeOk = async () => {
  const val = await formRef.value.validate();
  if (val) return false;

  if (state.module === "create") {
    usePositionCreateApi(state.form)
      .then(() => {
        Message.success("操作成功");
        emit("refresh");
      })
      .catch(() => {
        Message.warning("操作失败");
        emit("refresh");
      });
  } else {
    usePositionUpdateApi(state.form)
      .then(() => {
        Message.success("操作成功");
        emit("refresh");
      })
      .catch(() => {
        Message.warning("操作失败");
        emit("refresh");
      });
  }
};

const handleOk = () => {
  state.visible = false;
  state.form = useForm();
};

const handleCancel = () => {
  state.visible = false;
  state.form = useForm();
};

defineExpose({
  open,
});
</script>
<style scoped lang="less"></style>
